#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# blipoc - Blip On Console
#
# author: Cezary Statkiewicz (cezio [at] thelirium.net)
# website: http://code.google.com/p/blipoc/
#
# version: $Id$

import sys, atexit, curses, time, datetime
from pprint import pprint
import thread, threading
import pblipoc.api

def set_status(cli_options, config):
    username, password = config.get('user', 'username'), config.get('user', 'password')
    status = cli_options.set_status.decode(config.get('settings', 'encoding')).encode('utf-8')
    u = pblipoc.api.Update()
    u.set_credentials(username, password)
    data = u.set(status)
    pprint(data)

def friends(cli_options, config):
	username, password = config.get('user', 'username'), config.get('user', 'password')
	u = pblipoc.api.User()
	u.set_credentials(username, password)
	data = u.friends()
	_s = u'Przyjaciele użytkownika %s'%username
	print _s.encode(config.get('settings', 'encoding'))
	for f in data:
		_s = '\t%s [%s] @ %s: \n\t\t%s'%(f.login, f.id, getattr(f.current_status, 'created_at', ''), getattr(f.current_status, 'body', ''))
		try:
			print _s.encode(config.get('settings', 'encoding'))
		except UnicodeEncodeError, e:
			print _s.encode('utf-8')
	
def dashboard(cli_options, config):
    username, password = config.get('user', 'username'), config.get('user', 'password')
    if cli_options:
        dashboard = cli_options.dashboard
    else:
        dashboard = None
    u = pblipoc.api.Update()
    u.set_credentials(username, password)
    data = u.dashboard(dashboard)
    _s = u'Kokpit użytkownika %s'%username
    print _s.encode(config.get('settings', 'encoding'))
    #pprint(data)
    data.reverse()
    for d in data:
        _s = 'od: %s data: %s (transport: %s)\n\t%s\n'%( d['src_user']['login'], d['created_at'], d['transport']['name'], d['body'])
        try:
            print _s.encode(config.get('settings', 'encoding'))
        except UnicodeEncodeError, e:
            print _s.encode('utf-8')

def user(cli_options, config):
	username, password = config.get('user', 'username'), config.get('user', 'password')
	user_id  = None
	if cli_options and cli_options.user:
		user_id = cli_options.user
	u = pblipoc.api.User()
	u.set_credentials(username, password)
	data = u.users(user_id)
	if not data:
		_s = u'Nie znaleziono użytkownika o id %s'%user_id
		print _s.encode(config.get('settings', 'encoding'))
		return
	if getattr(data.current_status, 'body', ''):
		_s = u'Informacja o użytkowniku %s [%s] \n\t%s:\n\t %s'%(data.login,
													data.id,
													getattr(data.current_status, 'created_at', ''),
													getattr(data.current_status, 'body', ''))
		print _s.encode(config.get('settings', 'encoding'))
	else:
		_s = u'Informacja o użytkowniku %s [%s] \n\t(nie ma ustawionego statusu)'%(data.login,
													data.id)
		print _s.encode(config.get('settings', 'encoding'))

	
	

class CommandQueue(threading.Thread):
	def __init__(self, after_callback = None, max_commands = 5, *args, **kwargs):
		threading.Thread.__init__(self, *args, **kwargs)
		self._commands = []
		self.lock = threading.Lock()
		self._close = False
		self.after_callback = after_callback
		self.max_commands = max_commands
	
	def add_command(self, cmd, *args, **kwargs):
		self.lock.acquire()
		self._commands.append((cmd, args, kwargs,))
		self.lock.release()
		
	def close(self):
		print 'closing...'
		self._close = True
		
	def run(self):
		while not self._close:
			time.sleep(0.5)
			print 'tasks..', len(self._commands)
			while len(self._commands):
				self.lock.aquire()
				counter = 0
				while len(self._commands):
					if counter> self.max_commands:
						break
					cmd = self._commands.pop()
					cmd[0](*cmd[1], **cmd[2])
					counter += 1
				self.lock.release()
		if self.after_callback:
			self.after_callback()

class CommandDispatcher(object):
	commands = []
	def __init__(self):
		pass
	
	def install_command(self, cmd_func, *args, **kwargs):
		"""
		"""
		CommandDispatcher.commands.append(( cmd_func, args, kwargs,))

	def run(self):
		"""
		"""
		while len(CommandDispatcher.commands):
			cmd = CommandDispatcher.commands.pop(0)
			cmd[0]( *cmd[1], **cmd[2])

	def parse_commands(self, cli_options, config):
		"""
		parsuje polecenia z cli
		 - ustawienie statusu,
		 - pobranie dashboarda
		 - pobranie listy przyjaciół
		 
		 
		instaluje polecenia
		"""
		if getattr(cli_options, 'dashboard', None):
			self.install_command(dashboard, cli_options, config)
		if getattr(cli_options, 'set_status', None):
			self.install_command(set_status, cli_options, config)
		if getattr(cli_options, 'friends', None):
			self.install_command(friends, cli_options, config)
		if getattr(cli_options, 'user', None):
			self.install_command(user, cli_options, config)



class BlipocApp(object):
	"""
	interaktywna część
	"""
	def __init__(self, commands):
		self.commands = commands
		self._screen_cmds = []
		atexit.register(self.__del__)
		self.queue = CommandQueue()
		
	def run(self):
		"""
		"""
		print 'run..'
		# curses init
		#self.stdscr = curses.initscr()
		#curses.noecho()
		#curses.cbreak()
		#self.stdscr.keypad(1)
		self.queue.start()
		
		time.sleep(1)
		
	def __del__(self):
		self.queue.close()
		if self.queue.isAlive():
			self.queue.join(0.1)
		#curses.endwin()
		
		